<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
      <el-breadcrumb-item>网格员人员管理列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :inline="true" :model="queryForm" size="large" style="margin-top: 20px" class="demo-form-inline">
      <el-form-item label="省区域">
        <el-select v-model="queryForm.provinceName" @change="changeProvince" style="width: 120px">
          <el-option v-for="province in provinceArr" :key="province.provinceId" :label="province.provinceName" :value="province.provinceName" />
        </el-select>
      </el-form-item>

      <el-form-item label="市区域">
        <el-select v-model="queryForm.cityName" style="width: 120px">
          <el-option v-for="city in cityArr" :key="city.cityId" :label="city.cityName" :value="city.cityName" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="queryForm.state" style="width: 120px">
          <el-option label="-- 全部 --" :value="null" />
          <el-option label="工作状态" :value="0" />
          <el-option label="非工作状态" :value="1" />
          <el-option label="其它" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名搜索">
        <el-input v-model="queryForm.gmName" placeholder="请输入姓名" style="width: 150px" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="danger" @click="clear">清空</el-button>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="success" @click="openAddDialog">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="pageResponseDto.list" style="width: 100%;" :cell-style="{ padding: '6px' }" empty-text="无数据">
      <el-table-column prop="gmId" label="编号" width="80" />
      <el-table-column prop="gmName" label="姓名" />
      <el-table-column prop="gmCode" label="登录编码"/>
      
      <el-table-column prop="tel" label="联系电话" />
      <el-table-column prop="provinceName" label="所在省" />
      <el-table-column prop="cityName" label="所在市" />
      <el-table-column prop="remarks" label="备注"/>
      <el-table-column prop="state" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.state === 0" type="success">工作状态</el-tag>
          <el-tag v-else-if="scope.row.state === 1" type="info">非工作状态</el-tag>
          <el-tag v-else type="warning">其它</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editEvent(scope.row)">修改状态</el-button>
          <el-button link type="danger" size="small" @click="deleteEvent(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next, total"
          :total="pageResponseDto.totalRow"
          :page-size="store.state.maxPageNum"
          style="margin-top: 20px"
          v-model:current-page="pageNum"
      />
    </div>

    <!--新增弹窗表单-->
    <el-dialog v-model="showAddDialog" title="新增网格员" width="500px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="姓名" required>
          <el-input v-model="addForm.gmName" />
        </el-form-item>

        <el-form-item label="登录编码" required>
          <el-input v-model="addForm.gmCode"  />
        </el-form-item>
        <el-form-item label="登录密码" >
          <el-input v-model="addForm.password" disabled/>
        </el-form-item>

        <el-form-item label="联系电话" required>
          <el-input v-model="addForm.tel" />
        </el-form-item>

        <el-form-item label="省区域" required>
          <el-select v-model="addForm.provinceName" @change="onAddProvinceChange" style="width: 200px">
            <el-option v-for="item in provinceArr" :key="item.provinceId" :label="item.provinceName" :value="item.provinceName" />
          </el-select>
        </el-form-item>

        <el-form-item label="市区域" required>
          <el-select v-model="addForm.cityName" style="width: 200px">
            <el-option v-for="item in addDialogCityArr" :key="item.cityId" :label="item.cityName" :value="item.cityName" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" required>
          <el-input v-model="addForm.remarks" style="width: 400px">
          
          </el-input>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="addForm.state" style="width: 200px">
            <el-option label="工作状态" :value="0" />
            <el-option label="非工作状态" :value="1" />
            <el-option label="其它" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改状态弹窗 -->
    <el-dialog v-model="showStateDialog" title="修改状态" width="400px">
      <el-form :model="stateForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="stateForm.gmName" disabled />
        </el-form-item>
        
        <el-form-item label="当前状态">
          <el-tag 
            :type="stateForm.currentState === 0 ? 'success' : stateForm.currentState === 1 ? 'info' : 'warning'"
          >
            {{ stateForm.currentState === 0 ? '工作状态' : stateForm.currentState === 1 ? '非工作状态' : '其它' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="新状态" required>
          <el-select v-model="stateForm.newState" style="width: 200px" placeholder="请选择新状态">
            <el-option label="工作状态" :value="0">
              <el-tag type="success">工作状态</el-tag>
            </el-option>
            <el-option label="非工作状态" :value="1">
              <el-tag type="info">非工作状态</el-tag>
            </el-option>
            <el-option label="其它" :value="2">
              <el-tag type="warning">其它</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showStateDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmStateChange" :disabled="stateForm.newState === stateForm.currentState">确认修改</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {reactive, ref, inject, watch} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';


const store = useStore();
const router = useRouter();
const axios = inject("axios");
//增加人员

// 弹窗开关
const showAddDialog = ref(false);
const showStateDialog = ref(false);

// 新增表单
const addForm = ref({
  gmName: '',
  gmCode: '',
  password: '123', // 默认密码
  tel: '',
  provinceName: null,
  cityName: null,
  remarks: '',
  state: 0
});

// 状态修改表单
const stateForm = ref({
  gmId: null,
  gmName: '',
  currentState: null,
  newState: null
});

// 弹窗里用的市列表
const addDialogCityArr = ref([]);

// 打开新增弹窗
const openAddDialog = () => {
  showAddDialog.value = true;
  // 重置表单
  addForm.value.gmName = '';
  addForm.value.gmCode = '';
  addForm.value.remarks = '';
  addForm.value.password = '123'; // 默认密码
  addForm.value.tel = '';
  addForm.value.provinceName = null;
  addForm.value.cityName = null;
  addForm.value.state = 0;
  // 清空城市列表
  addDialogCityArr.value = [];
};

// 省切换 - 新增表单
const onAddProvinceChange = (provinceName) => {
  addForm.value.cityName = null;
  // 根据省份名称找到对应的省份ID
  const province = provinceArr.value.find(p => p.provinceName === provinceName);
  if (province) {
    axios.post('/gridCity/listGridCityByProvinceId', { provinceId: province.provinceId }).then(res => {
      addDialogCityArr.value = res.data;
    });
  }
};

// 提交
const submitAdd = () => {
  axios.post('/gridMember/addGridmember', addForm.value).then(() => {
    ElMessage.success('新增成功');
    showAddDialog.value = false;
    // 刷新主列表
    listGridPersonnelPage(1);
  }).catch(() => {
    ElMessage.error('登录编码重复');
  });
};

// 查询表单
const queryForm = ref({
  provinceName: null,
  cityName: null,
  state: null,
  gmName: ""
});

// 分页
const pageNum = ref(1);
watch(pageNum, (newValue) => {
  listGridPersonnelPage(newValue);
});

// 省市选项
const provinceArr = ref([]);
const cityArr = ref([]);

// 分页结果
const pageResponseDto = ref();

// 列表
const listGridPersonnelPage = (pageNum) => {
  const param = {
    provinceName: queryForm.value.provinceName || "",
    cityName: queryForm.value.cityName || "",
    state: queryForm.value.state,
    gmName: queryForm.value.gmName || "",
    pageNum: pageNum,
    maxPageNum: store.state.maxPageNum,
    beginNum: (pageNum - 1) * store.state.maxPageNum
  };
  axios.post("gridMember/listGridmember", param).then((res) => {
    pageResponseDto.value = res.data;
  });
};

// 获取省
const listGridProvinceAll = () => {
  axios.post("gridProvince/listGridProvinceAll").then((res) => {
    provinceArr.value = res.data;
    provinceArr.value.unshift({provinceId: 0, provinceName: "-- 全部 --"});
    if (provinceArr.value.length > 1) {
      listGridCityByProvinceId(provinceArr.value[1].provinceId);
    }
  });
};

// 获取市
const listGridCityByProvinceId = (provinceId) => {
  axios.post("gridCity/listGridCityByProvinceId", {provinceId}).then((res) => {
    cityArr.value = res.data;
    cityArr.value.unshift({cityId: 0, cityName: "-- 全部 --"});
  });
};

// 省切换 - 查询表单
const changeProvince = (provinceName) => {
  queryForm.value.cityName = null; // 重置市区域选择
  // 根据省份名称找到对应的省份ID，然后获取城市列表
  const province = provinceArr.value.find(p => p.provinceName === provinceName);
  if (province) {
    listGridCityByProvinceId(province.provinceId);
  }
};

// 初始化
const init = () => {
  listGridProvinceAll();
  listGridPersonnelPage(1);
};
init();

// 清空
const clear = () => {
  queryForm.value.provinceName = null;
  queryForm.value.cityName = null;
  queryForm.value.state = null;
  queryForm.value.gmName = "";
  pageNum.value = 1;
  
  // 清空后无条件查询
  const param = {
    provinceName: "",
    cityName: "",
    state: null,
    gmName: "",
    pageNum: 1,
    maxPageNum: store.state.maxPageNum,
    beginNum: 0
  };
  axios.post("gridMember/listGridmember", param).then((res) => {
    pageResponseDto.value = res.data;
  });
};

// 查询
const query = () => {
  pageNum.value = 1;
  listGridPersonnelPage(1);
};

// 编辑状态
const editEvent = (row) => {
  // 设置状态表单数据
  stateForm.value.gmId = row.gmId;
  stateForm.value.gmName = row.gmName;
  stateForm.value.currentState = row.state;
  stateForm.value.newState = row.state; // 默认选择当前状态
  
  // 显示状态修改弹窗
  showStateDialog.value = true;
};

// 确认状态修改
const confirmStateChange = () => {
  if (stateForm.value.newState === stateForm.value.currentState) {
    ElMessage.info('状态未发生变化');
    return;
  }
  
  updateGridMemberState(stateForm.value, stateForm.value.newState);
  showStateDialog.value = false;
};

// 更新网格员状态
const updateGridMemberState = (formData, newState) => {
  axios.post('/gridMember/updateGridmember', {
    gmId: formData.gmId,
    gmName: formData.gmName,
    gmCode: formData.gmCode,
    password: formData.password,
    provinceId: formData.provinceId,
    cityId: formData.cityId,
    tel: formData.tel,
    state: newState,
    remarks: formData.remarks
  }).then(() => {
    ElMessage.success('状态修改成功');
    listGridPersonnelPage(pageNum.value); // 刷新当前页
  }).catch(() => {
    ElMessage.error('状态修改失败');
  });
};

// 删除
const deleteEvent = (row) => {
  ElMessageBox.confirm(
      `确认要删除姓名为「${row.gmName}」的网格员吗？`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 调用后端删除接口
        axios.get(`/gridMember/deleteGridmember/${row.gmId}`)
            .then(() => {
              ElMessage.success('删除成功');
              listGridPersonnelPage(pageNum.value);  // 刷新当前页而不是第一页
            })
            .catch(() => {
              ElMessage.error('删除失败');
            });
      })
      .catch(() => {
        // 用户点了取消
      });
};
</script>





<style scoped>
.pagination {
  display: flex;
  justify-content: center;
}

/* 状态弹窗样式美化 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-select .el-tag {
  margin-right: 8px;
}

/* 确认修改按钮禁用状态样式 */
.el-button:disabled {
  opacity: 0.5;
}
</style>

